﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mani.Patient.Business.Services;
using NHibernate;
using NHibernate.Expression;
using Mani.Patient.Business.Domain.Entity;

namespace Mani.Patient.Business.Dao {

    public interface IPatientDao : IDao<Mani.Patient.Business.Domain.Entity.Patient> {

        IList<Mani.Patient.Business.Domain.Entity.Patient> FindPatients(int pageSize, int pageNumber, string sort, bool asc, string patientName, File file);
        int CountFindPatients(string patientName, File file);
    }

    public class PatientDao : DaoBase<Mani.Patient.Business.Domain.Entity.Patient>, IPatientDao {

        public int CountFindPatients(string patientName, File file) {
            ICriteria criteria = base.Session.CreateCriteria(typeof(Patient.Business.Domain.Entity.Patient));

            if (file != null) {
                criteria.Add(Expression.Eq("Id", file.Id));
            }

            if (!String.IsNullOrEmpty(patientName)) {
                criteria.Add(Expression.Like("PatientName", patientName, MatchMode.Anywhere));
            }

            return criteria.SetProjection( Projections.Count("Id") ).UniqueResult<int>();
        }

        public IList<Mani.Patient.Business.Domain.Entity.Patient> FindPatients(int pageSize, int pageNumber, string sort, bool asc, string patientName, File File) {
            ICriteria criteria = base.Session.CreateCriteria(typeof(Patient.Business.Domain.Entity.Patient));
            Order order = new Order(sort, asc);
            criteria.AddOrder(order);

            if (File != null) {
                criteria.Add(Expression.Eq("Id", File.Id));
            }

            if (!String.IsNullOrEmpty(patientName)) {
                criteria.Add(Expression.Like("PatientName", patientName, MatchMode.Anywhere));
            }

            return criteria.SetMaxResults(pageSize).SetFirstResult(pageSize * pageNumber).List<Patient.Business.Domain.Entity.Patient>();

        }
    }
}
